package turritopsis

import (
	"ebbflow/pkg/adkr"
	"fmt"
	"log"
	"time"
)

// StubACS returns a minimal ACS hook that immediately decides an empty batch.
// This is useful for wiring and end-to-end smoke tests before integrating sDumbo.
func StubACS(logger *log.Logger) ACSFunc {
	if logger == nil { logger = log.Default() }
	return func(sid string, input []byte) ([][]byte, error) {
		logger.Printf("StubACS sid=%s returning empty batch", sid)
		return [][]byte{}, nil
	}
}

// NewKeyRefreshFuncUsingChannels builds a KeyRefreshFunc that runs a single ADKR key-refresh round
// using provided shared message channels (from the host network layer) and a per-round config builder.
// The function blocks until the round completes or times out.
func NewKeyRefreshFuncUsingChannels(
	krConfigBuilder func(round int) adkr.KeyRefreshConfig,
	msgInCh <-chan adkr.Message,
	msgOutCh chan<- adkr.Message,
	logger *log.Logger,
) KeyRefreshFunc {
	if logger == nil { logger = log.Default() }
	return func(round int) (*adkr.KeyRefreshOutput, error) {
		cfg := krConfigBuilder(round)
		outCh := make(chan adkr.KeyRefreshOutput, 1)
		p := adkr.NewKeyRefreshProtocol(cfg, msgInCh, msgOutCh, outCh, logger)
		// Run in background and wait
		done := make(chan error, 1)
		go func() { done <- p.Run() }()
		select {
		case res := <-outCh:
			return &res, nil
		case err := <-done:
			if err != nil { return nil, err }
			return nil, fmt.Errorf("key refresh finished without output")
		case <-time.After(90 * time.Second):
			return nil, fmt.Errorf("key refresh timeout")
		}
	}
}


